package com.zdkj.subway.st.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.st.dto.in.SwStAuditDTO;
import com.zdkj.subway.st.entity.PkProdparams;
import com.zdkj.subway.st.entity.SwStPlanDay;
import com.zdkj.subway.st.service.PkCardfileinfoService;
import com.zdkj.subway.st.service.PkProdparamsService;
import com.zdkj.subway.st.service.SwStPlanDayService;
import com.zdkj.subway.st.util.JdbcUtil;
import com.zdkj.subway.st.util.LocalDateConverter;
import com.zdkj.subway.st.util.LocalDateTimeConverter;
import com.zdkj.subway.st.util.SubwayStConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@AllArgsConstructor
@RequestMapping("/swStPlanDay")
@Api(value = "swStPlanDay", tags = "周计划管理")
@Slf4j
public class SwStPlanDayController {
    private final SwStPlanDayService swStPlanDayService;
    private final PkProdparamsService pkProdparamsService;
    private final PkCardfileinfoService pkCardfileinfoService;
    @GetMapping("/{id}")
    public R getById(@PathVariable String id) {
        return R.ok(swStPlanDayService.getById(id));
    }

    @GetMapping("/page/{type}")
    public R<IPage> getDictPage(Page page, SwStPlanDay swStPlanDay, @PathVariable String type) {
        //swStPlanDay.setPlanType(type);
        /*LambdaQueryWrapper<SwStPlanDay> lambdaQueryWrapper = Wrappers.lambdaQuery(swStPlanDay)
                .eq(SwStPlanDay::getDisplay, true);*/
        //QueryWrapper<SwStPlanDay> lambdaQueryWrapper = Wrappers.query(swStPlanDay);
        QueryWrapper<SwStPlanDay> lambdaQueryWrapper = new QueryWrapper<>();
        lambdaQueryWrapper.lambda().eq(SwStPlanDay::getPlanType,type);
        if (null != swStPlanDay.getActualFinishTime()) {
            lambdaQueryWrapper.lambda().likeRight(SwStPlanDay::getActualFinishTime,
                    swStPlanDay.getActualFinishTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
        if(null != swStPlanDay.getPlanMonth()){
            lambdaQueryWrapper.lambda().eq(SwStPlanDay::getPlanMonth,swStPlanDay.getPlanMonth());
        }
        if(null != swStPlanDay.getWorkTime()){
            lambdaQueryWrapper.lambda().eq(SwStPlanDay::getWorkTime,swStPlanDay.getWorkTime());
        }
        if(null != swStPlanDay.getTicketType()){
            lambdaQueryWrapper.lambda().eq(SwStPlanDay::getTicketType,swStPlanDay.getTicketType());
        }
        if(null != swStPlanDay.getTicketName()){
            lambdaQueryWrapper.lambda().eq(SwStPlanDay::getTicketName,swStPlanDay.getTicketName());
        }
        if(null != swStPlanDay.getIsFinish()){
            lambdaQueryWrapper.lambda().eq(SwStPlanDay::getIsFinish,swStPlanDay.getIsFinish());
        }
        if(null != swStPlanDay.getCheckStatus()){
            lambdaQueryWrapper.lambda().eq(SwStPlanDay::getCheckStatus,swStPlanDay.getCheckStatus());
        }
        if(null != swStPlanDay.getTaskType()){
            lambdaQueryWrapper.lambda().eq(SwStPlanDay::getTaskType,swStPlanDay.getTaskType());
        }
		if(null != swStPlanDay.getIsInstock()){
            lambdaQueryWrapper.lambda().eq(SwStPlanDay::getIsInstock,swStPlanDay.getIsInstock());
        }
		if(null != swStPlanDay.getIsOutstock()){
            lambdaQueryWrapper.lambda().eq(SwStPlanDay::getIsOutstock,swStPlanDay.getIsOutstock());
        }
        if(null != swStPlanDay.getOperator()){
            lambdaQueryWrapper.lambda().eq(SwStPlanDay::getOperator,swStPlanDay.getOperator());
        }
        if(StringUtils.isNotEmpty(swStPlanDay.getNumbers())){
            lambdaQueryWrapper.lambda().like(SwStPlanDay::getNumbers,swStPlanDay.getNumbers());
        }
		if(StringUtils.isNotEmpty(swStPlanDay.getCheckApproveStatus())){
            lambdaQueryWrapper.lambda().eq(SwStPlanDay::getCheckApproveStatus,swStPlanDay.getCheckApproveStatus());
        }
		if(StringUtils.isNotEmpty(swStPlanDay.getCheckPersonName())){
            lambdaQueryWrapper.lambda().like(SwStPlanDay::getCheckPersonName,swStPlanDay.getCheckPersonName());
        }
		 if (null != swStPlanDay.getCheckTime()) {
            lambdaQueryWrapper.lambda().likeRight(SwStPlanDay::getCheckTime,
                    swStPlanDay.getCheckTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
        lambdaQueryWrapper.lambda().eq(SwStPlanDay::getDisplay, true);
        lambdaQueryWrapper.orderByDesc("CREATE_TIME");
        return R.ok(swStPlanDayService.page(page, lambdaQueryWrapper));
    }

    @GetMapping("/pages/{type}")
    public R getWeekForPage(Page page, SwStPlanDay swStPlanDay, @PathVariable String type) {
        swStPlanDay.setPlanType(type);
        LambdaQueryWrapper<SwStPlanDay> lambdaQueryWrapper = Wrappers.lambdaQuery(swStPlanDay);
        if (null != swStPlanDay.getActualFinishTime()) {
            lambdaQueryWrapper.likeRight(SwStPlanDay::getActualFinishTime,
                    swStPlanDay.getActualFinishTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
        return R.ok(swStPlanDayService.list(lambdaQueryWrapper));
    }

    @SysLog("新增车票日计划")
    @PostMapping
    public R save(@Valid @RequestBody SwStPlanDay swStPlanDay) {
        PigxUser user = SecurityUtils.getUser();
        swStPlanDay.setCheckStatus(SubwayStConstants.AUDIT_STATUS_PASS);
        swStPlanDay.setCreatorId((long) user.getId());
        swStPlanDay.setCreatorName(user.getUsername());
        swStPlanDay.setCheckSubmit(SubwayStConstants.SUBMIT_STATUS_WAIT);
        return R.ok(swStPlanDayService.save(swStPlanDay));
    }

    @SysLog("批量新增车票日计划")
    @PostMapping("/saveAll")
    public R saveAll(@Valid @RequestBody List<SwStPlanDay> swStPlanDayList) {
        PigxUser user = SecurityUtils.getUser();
        for (SwStPlanDay swStPlanWeek : swStPlanDayList) {
            swStPlanWeek.setCheckStatus(SubwayStConstants.AUDIT_STATUS_PASS);
            swStPlanWeek.setCreatorId((long) user.getId());
            swStPlanWeek.setCreatorName(user.getUsername());
            swStPlanWeek.setCheckSubmit(SubwayStConstants.SUBMIT_STATUS_WAIT);
            swStPlanDayService.save(swStPlanWeek);
        }
        return R.ok(swStPlanDayList.size());
    }

    @SysLog("删除车票日计划")
    @DeleteMapping("/{id}")
    public R removeById(@PathVariable String id) {
        return R.ok(swStPlanDayService.removeById(id));
    }

    @PutMapping
    @SysLog("修改车票日计划")
    public R updateById(@Valid @RequestBody SwStPlanDay swStPlanDay) throws SQLException {
        // todo 去掉车票起止号校验和匹配查询
        //boolean b = ("1".equals(swStPlanDay.getTaskType()) || "2".equals(swStPlanDay.getTaskType())) &&
        //        ("是".equals(swStPlanDay.getEsIsInitialization()));
        //if(b){
        //    if(StringUtils.isEmpty(swStPlanDay.getStartEndNo()) || !swStPlanDay.getStartEndNo().contains("/")){
        //        return R.failed("请按照规范格式输入起号/止号！");
        //    }else {
        //        String startEndNo = swStPlanDay.getStartEndNo();
        //        String[] split = startEndNo.split(",");
        //        for (String s : split) {
        //            String[] split1 = s.split("\\/");
        //            LambdaQueryWrapper<PkCardfileinfo> between =
        //                    Wrappers.<PkCardfileinfo>lambdaQuery().between(PkCardfileinfo::getCardcode, split1[0],
        //                            split1[1]);
        //            List<PkCardfileinfo> list = pkCardfileinfoService.list(between);
        //            if(CollectionUtil.isEmpty(list)){
        //               return R.failed("未找到该号段记录，请检查是否正确！");
        //            }
        //        }
        //    }
        //}

        if(swStPlanDay.getTotalNumber()!=null){
            if(swStPlanDay.getTotalNumber()>=swStPlanDay.getTicketNumber()){
                swStPlanDay.setIsFinish("1");
            }else{
                swStPlanDay.setIsFinish("0");
            }
        }
        if(swStPlanDay.getDistribuNumber()!=null){
            if(swStPlanDay.getDistribuNumber()>=swStPlanDay.getTicketNumber()){
                swStPlanDay.setIsFinish("1");
            }else{
                swStPlanDay.setIsFinish("0");
            }
        }
        //处理日期置null操作
        if("1".equals(swStPlanDay.getTaskType()) || "4".equals(swStPlanDay.getTaskType())){
            swStPlanDay.setEsStartDate(null);
            swStPlanDay.setEsEndDate(null);
            JdbcUtil.exeSqlCrud("update sw_tk_public_plan_day set ES_START_DATE = null, ES_END_DATE = null where ID = '"+swStPlanDay.getId()+"'");
        }
        return R.ok(swStPlanDayService.updateById(swStPlanDay));
    }

    @PutMapping("/submit")
    @SysLog("提交车票日计划")
    public R submit(@Valid @RequestBody List<Integer> ids) {
        return R.ok(swStPlanDayService.submitBatch(ids));
    }

    @PutMapping("/applyed")
    @SysLog("车票日计划申请修改")
    @PreAuthorize("@pms.hasPermission('st_plan_day_clean_plan_apply')")
    public R applyed(@Valid @RequestBody List<Integer> ids) {
        return R.ok(swStPlanDayService.applyedBatch(ids));
    }

    @PutMapping("/approved")
    @SysLog("车票日计划审批修改")
    @PreAuthorize("@pms.hasPermission('st_plan_day_clean_plan_approve')")
    public R approved(@Valid @RequestBody List<Integer> ids) {
        return R.ok(swStPlanDayService.approvedBatch(ids));
    }

    @PutMapping("/inputDetailSubmit")
    @SysLog("加入车票入库")
    public R inputDetailSubmit(@Valid @RequestBody List<Integer> ids) {
        return R.ok(swStPlanDayService.inputDetailSubmitBatch(ids));
    }

    @PutMapping("/outputDetailSubmit")
    @SysLog("加入车票出库")
    public R outputDetailSubmit(@Valid @RequestBody List<Integer> ids) {
        return R.ok(swStPlanDayService.outputDetailSubmitBatch(ids));
    }

    @PutMapping("/audit")
    @SysLog("审批车票日计划")
    public R audit(@Valid @RequestBody SwStAuditDTO swStAuditDTO,Integer id) {
        return R.ok(swStPlanDayService.auditBatch(swStAuditDTO,id));
    }

    @GetMapping("/export")
    @SysLog("导出车票日计划")
    public void exportExcel(SwStPlanDay swStPlanDay, HttpServletResponse response) throws IOException {
        List<SwStPlanDay> swStCycleList = swStPlanDayService.list(Wrappers.query(swStPlanDay));
        String fileName = URLEncoder.encode("车票日计划", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SwStPlanDay.class).registerConverter(new LocalDateTimeConverter())
                .registerConverter(new LocalDateConverter()).sheet("车票日计划").doWrite(swStCycleList);
    }

    /*@GetMapping("/export")
    @SysLog("导出车票日计划")
    public void exportExcel(SwStPlanDay swStPlanDay, HttpServletResponse response) throws IOException {
        List<SwStPlanDay> swStCycleList = swStPlanDayService.list(Wrappers.query(swStPlanDay));
        IExcelExport excelExport = SpringContextHolder.getBean("commonExcelExport");
        Workbook workbook = excelExport.parse(swStCycleList);
        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            log.error("", e);
        }
    }*/

    /**
     * 根据es产品类型表的产品主类型查对应的子类型
     * @param productType
     * @return
     */
    @ApiOperation(value = "根据es产品类型表的产品主类型查对应的子类型", notes = "根据es产品类型表的产品主类型查对应的子类型")
    @SysLog("根据es产品类型表的产品主类型查对应的子类型")
    @GetMapping("/dictProductTypeAll/{productType}")
    public R getDictProductTypeAll(@PathVariable String productType) {
        List<PkProdparams> list =
                pkProdparamsService.listProductSubTypeAll(productType);
        return R.ok(list);
    }

    /**
     * 根据es产品类型表查产品主类型
     * @param
     * @return
     */
    @ApiOperation(value = "根据es产品类型表查产品主类型", notes = "根据es产品类型表查产品主类型")
    @SysLog("根据es产品类型表查产品主类型")
    @GetMapping("/dictProductTypeAll")
    public R getDictProductTypeOfAll() {
        List<PkProdparams> list =
                pkProdparamsService.listProductTypeAll();
        return R.ok(list);
    }
}
